import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    // start progress bar
    NProgress.start()
    // set page title
    document.title = to.meta ? to.meta.title : '管理后台'
    // console.log('[permission]')

    if (whiteList.indexOf(to.path) > -1) {
        next()
    } else {
        const hasToken = getToken()
        if (hasToken) {
            if (to.path === '/login') {
                next()
            } else {
                const hasGetUserInfo = store.getters.userInfo.role
                if (hasGetUserInfo) {
                    next()
                    NProgress.done()
                } else {
                    next()
                    try {
                        await store.dispatch('user/getInfo')
                        next({...to, replace: true})
                    } catch (error) {
                        NProgress.done()
                    }
                }
            }
        } else {
            next(`/login?redirect=${to.fullPath}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
